<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-02-05 09:08:10
 * @LastEditors: william
 * @LastEditTime: 2025-08-12 10:56:46
-->
<template>
  <el-config-provider :locale="locale">
    <router-view />
  </el-config-provider>
</template>

<script setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import defaultSettings from '@/settings'
import { getLanguage } from '@/lang/index'

const locale = ref(zhCn)
const appStore = useAppStore()
const { language } = storeToRefs(appStore)
const { eventSource } = storeToRefs(useUserStore())

// 监听语言变化
watch(
  language,
  newLang => {
    // 设置页面标题
    document.title =
      newLang === 'en' ? defaultSettings.en_title : defaultSettings.title
  },
  { immediate: true }
)

// 在组件挂载时设置主题和语言
onMounted(() => {
  appStore.setTheme(localStorage.getItem('theme-color') || 'theme-white')
  appStore.setLanguage(getLanguage())
  locale.value = getLanguage() === 'zh' ? zhCn : en
  window.addEventListener('beforeunload', function (event) {
    // 可以在这里执行一些清理操作
    console.log('页面即将刷新或关闭')

    // 现代浏览器要求设置returnValue才能显示确认对话框
    // event.preventDefault()
    // event.returnValue = '' // 必须设置这个值，但可以是空字符串
    eventSource.value && eventSource.value.close()
  })
})

onBeforeUnmount(() => {
  eventSource.value && eventSource.value.close()
})
</script>
